package com.itmuch.youran.service.redis;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;

/**
 * 本类演示了redis的增删改查 参考文档: http://stamen.iteye.com/blog/1907984
 *
 * @author zhouli
 */
@Service
public class RedisService<T> {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * @param key key
     * @param value 需要设入的对象
     * @param timeout 超时时间
     */
    public void set(final String key, final Object value, final Long timeout) {
        this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(value.getClass()));
        this.redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 根据key查询
     * @param key key
     * @param clz 查询对象的类
     * @return 查询到的结果
     */
    @SuppressWarnings("unchecked")
    public T getByKey(final String key, Class<T> clz) {
        this.redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<T>(clz));
        return (T) this.redisTemplate.opsForValue().get(key);
    }

    /**
     * 单条删除
     * @param key
     */
    public void delByKey(final String key) {
        this.redisTemplate.delete(key);
    }

    /**
     * 批量删除
     * @param keys
     */
    public void delByKeys(final List<String> keys) {
        this.redisTemplate.delete(keys);
    }

}
